import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import {
  getItem
} from "@/utils/storage"
Vue.use(VueRouter)

const routes = [{
    path: '/',
    name: 'Home',
    // component: Home
    redirect: '/admin/home'
  },

  // 登录
  {
    path: "/login",
    name: "/Login",
    component: () => import("../views/login/login.vue")

  },
  //注册路由
  {
    path: "/register",
    name: "Register",
    component: () => import("../views/login/register.vue")
  },
  // 管理页首页
  {
    path: "/admin",
    name: "Admin",
    component: () => import('../components/layou/Admin.vue'),
    children: [{
        path: "home",
        name: "adminHome",
        component: () => import("../views/admin/Home.vue")
      },
      {
        path: "question/list",
        name: "QuestionList",
        component: () => import("../views/admin/question/List.vue")
      }
    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
// 解决 elementUI 导航跳转时报错问题
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function (location) {
  return originalPush.call(this, location).catch(err => err)
}

// 导航守卫
// 
router.beforeEach((to, from, next) => {
  //to 要访问的路由
  // from 是一个路由
  // next() 想要继续做路由跳转，next函数的必须的
  // 管理页面是 /admin/xxx/xxx
  //定义规则
  const reg = /^\/admin\/*/;
  // 获取用户信息
  const userInfo = getItem("userInfo");
  // 如果访问的是管理路由
  if (reg.test(to.path)) {
    // 判断用户是否已经登录
    if (userInfo) {
      // 已经登录可以继续访问，
      next();
    } else {
      // 否则，跳转至登录页面
      next("/login");
    }
  }
  // 如果访问不是管理页面，可直接访问
  next();
})

export default router
